<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 页面头部 -->
    <div class="bg-white shadow-sm border-b">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <div class="flex items-center space-x-4">
            <button 
              @click="$router.go(-1)"
              class="p-2 text-gray-400 hover:text-gray-600 transition-colors"
            >
              <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd"/>
              </svg>
            </button>
            <h1 class="text-xl font-semibold text-gray-900">每日一题历史</h1>
          </div>
          <div class="flex items-center space-x-4">
            <button 
              @click="refreshData"
              class="px-4 py-2 text-sm bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
            >
              刷新
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 统计信息 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center">
                <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">总参与天数</p>
              <p class="text-2xl font-semibold text-gray-900">{{ history.length }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center">
                <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 8zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">已解决</p>
              <p class="text-2xl font-semibold text-gray-900">{{ solvedCount }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-yellow-500 rounded-full flex items-center justify-center">
                <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"/>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">解决率</p>
              <p class="text-2xl font-semibold text-gray-900">{{ solveRate }}%</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-purple-500 rounded-full flex items-center justify-center">
                <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd"/>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">连续天数</p>
              <p class="text-2xl font-semibold text-gray-900">{{ consecutiveDays }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 历史记录列表 -->
      <div class="bg-white rounded-lg shadow">
        <div class="px-6 py-4 border-b border-gray-200">
          <h2 class="text-lg font-medium text-gray-900">历史记录</h2>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="flex items-center justify-center py-12">
          <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="text-center py-12">
          <div class="text-red-500 mb-4">
            <svg class="w-12 h-12 mx-auto mb-2" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
            </svg>
            <p class="text-gray-600">{{ error }}</p>
            <button 
              @click="fetchHistory"
              class="mt-4 px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
            >
              重试
            </button>
          </div>
        </div>

        <!-- 历史记录内容 -->
        <div v-else-if="history.length > 0" class="divide-y divide-gray-200">
          <div 
            v-for="item in history" 
            :key="item.id"
            class="px-6 py-4 hover:bg-gray-50 transition-colors"
          >
            <div class="flex items-center justify-between">
              <div class="flex-1">
                <div class="flex items-center space-x-4">
                  <div class="flex items-center space-x-2">
                    <span class="text-sm text-gray-500">{{ formatDate(item.date) }}</span>
                    <span 
                      class="w-2 h-2 rounded-full" 
                      :class="getDifficultyColor(item.question.difficulty)"
                    ></span>
                    <span class="text-sm text-gray-600">{{ item.question.difficulty }}</span>
                  </div>
                  <div class="flex items-center space-x-1">
                    <svg 
                      v-if="item.is_solved" 
                      class="w-4 h-4 text-green-500" 
                      fill="currentColor" 
                      viewBox="0 0 20 20"
                    >
                      <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 8zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                    </svg>
                    <span 
                      class="text-sm font-medium"
                      :class="item.is_solved ? 'text-green-600' : 'text-gray-500'"
                    >
                      {{ item.is_solved ? '已解决' : '未解决' }}
                    </span>
                  </div>
                </div>
                
                <h3 class="mt-2 text-lg font-medium text-gray-900">
                  {{ item.question.title }}
                </h3>
                
                <div class="mt-2 flex items-center space-x-4 text-sm text-gray-500">
                  <span>尝试次数: {{ item.attempt_count }}</span>
                  <span v-if="item.solved_at">
                    解决时间: {{ formatDateTime(item.solved_at) }}
                  </span>
                  <span v-if="item.first_attempt_at">
                    首次尝试: {{ formatDateTime(item.first_attempt_at) }}
                  </span>
                </div>

                <!-- 标签 -->
                <div v-if="item.question.tags.length > 0" class="mt-2 flex flex-wrap gap-1">
                  <span 
                    v-for="tag in item.question.tags" 
                    :key="tag.id"
                    class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded-full"
                  >
                    {{ tag.name }}
                  </span>
                </div>
              </div>

              <div class="flex items-center space-x-2">
                <button 
                  @click="goToQuestion(item.question.slug)"
                  class="px-4 py-2 text-sm bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
                >
                  查看题目
                </button>
                <button 
                  v-if="item.submission_id"
                  @click="goToSubmission(item.submission_id)"
                  class="px-4 py-2 text-sm border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors"
                >
                  查看提交
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="text-center py-12">
          <div class="text-gray-400 mb-4">
            <svg class="w-12 h-12 mx-auto mb-2" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"/>
            </svg>
            <p class="text-gray-600">暂无历史记录</p>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="pagination && pagination.total_page > 1" class="px-6 py-4 border-t border-gray-200">
          <div class="flex items-center justify-between">
            <div class="text-sm text-gray-700">
              显示第 {{ (pagination.page - 1) * pagination.page_size + 1 }} - 
              {{ Math.min(pagination.page * pagination.page_size, pagination.total) }} 条，
              共 {{ pagination.total }} 条记录
            </div>
            <div class="flex items-center space-x-2">
              <button 
                @click="changePage(pagination.page - 1)"
                :disabled="pagination.page <= 1"
                class="px-3 py-1 text-sm border border-gray-300 rounded-md disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                上一页
              </button>
              <span class="px-3 py-1 text-sm text-gray-700">
                {{ pagination.page }} / {{ pagination.total_page }}
              </span>
              <button 
                @click="changePage(pagination.page + 1)"
                :disabled="pagination.page >= pagination.total_page"
                class="px-3 py-1 text-sm border border-gray-300 rounded-md disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUserDailyQuestionHistory, type UserDailyQuestionHistory, type PaginationInfo } from '@/api/dailyQuestion'

const router = useRouter()

// 响应式数据
const history = ref<UserDailyQuestionHistory[]>([])
const pagination = ref<PaginationInfo | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const currentPage = ref(1)
const pageSize = ref(10)

// 计算属性
const solvedCount = computed(() => {
  return history.value.filter(item => item.is_solved).length
})

const solveRate = computed(() => {
  if (history.value.length === 0) return 0
  return Math.round((solvedCount.value / history.value.length) * 100)
})

const consecutiveDays = computed(() => {
  let count = 0
  const sortedHistory = [...history.value].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
  
  for (const item of sortedHistory) {
    if (item.is_solved) {
      count++
    } else {
      break
    }
  }
  
  return count
})

// 获取历史记录
const fetchHistory = async () => {
  loading.value = true
  error.value = null
  
  try {
    const response = await getUserDailyQuestionHistory(currentPage.value, pageSize.value)
    history.value = response.history
    pagination.value = response.pagination
  } catch (err: any) {
    error.value = err.message || '获取历史记录失败'
    console.error('获取历史记录失败:', err)
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchHistory()
}

// 切换页面
const changePage = (page: number) => {
  if (page >= 1 && page <= (pagination.value?.total_page || 1)) {
    currentPage.value = page
    fetchHistory()
  }
}

// 跳转到题目详情页
const goToQuestion = (slug: string) => {
  router.push(`/questions/${slug}`)
}

// 跳转到提交详情页
const goToSubmission = (submissionId: number) => {
  router.push(`/submissions/${submissionId}`)
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取难度颜色
const getDifficultyColor = (difficulty: string) => {
  switch (difficulty) {
    case 'Easy':
      return 'bg-green-500'
    case 'Medium':
      return 'bg-yellow-500'
    case 'Hard':
      return 'bg-red-500'
    default:
      return 'bg-gray-500'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchHistory()
})
</script>
